package com.isunland.managesystem.common;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseOriginal;
import com.isunland.managesystem.ui.SplashActivity;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import org.json.JSONException;

public abstract class VolleyResponse implements Listener<String>, ErrorListener {

  private static final int STATUS_RESPONSE = 1;
  private static final int STATUS_ERROR = 2;
  private static final int STATE_IS_EXCUTE = 0;
  private Context mContext;
  private int state = STATE_IS_EXCUTE;

  @Deprecated public static <T> BaseOriginal<T> inflate(String json) {
    return new Gson().fromJson(json, new TypeToken<BaseOriginal<T>>() {
    }.getType());
  }

  public void setContext(Context context) {
    mContext = context;
  }

  /**
   * 默认联网错误处理.
   * 提示错误信息.可以重写ifToastError()关闭提示.
   */
  @Override public void onErrorResponse(VolleyError error) {
    changeState(STATUS_ERROR);
    MyUtils.dismissDialog();
    LogUtil.e("error", error);
    if (null != error && error.networkResponse != null) {
      LogUtil.i("HttpStatusCode=" + error.networkResponse.statusCode);
      if (error.networkResponse.statusCode == 302) {
        LogUtil.i("302重定向");
      }
    }

    //如果是报错重启后的重定向,自动登录.
    if (null != error && null != error.getMessage()) {

      String message = error.getMessage();
      LogUtil.e("erorMessage=" + message);
      if (message.contains("Too many redirects")) {
        reLogin();
      }
    }

    //提示信息.
    if (ifToastError()) {
      if (error != null) {
        if (error.networkResponse == null) {
          if (error.getClass().equals(TimeoutError.class)) {
            ToastUtil.show(R.string.timeOutError);
            //					Toast.makeText(mContext, R.string.timeOutError, To ast.LENGTH_SHORT)
            //					.show();
          } else {
            ToastUtil.show(R.string.noConnectionToServer);
          }
        } else {
          ToastUtil.show(R.string.noConnectionToServer);
        }
      }
    }

    try {
      onVolleyError(error);
    } catch (Exception e) {
      // Auto-generated catch block
      LogUtil.e("onErrorResponse", e);
    }
  }

  private void changeState(int newStatus) {
    this.state = newStatus;
  }

  /**
   * 是否显示错误提示
   */
  public boolean ifToastError() {
    return true;
  }

  public abstract void onVolleyError(VolleyError arg0);

  /**
   * 默认联网返回数据处理.
   * 如果是重定向到登陆页面,提示重新登陆.
   * 提示json异常.
   */
  @Override public void onResponse(String arg0) {
    MyUtils.dismissDialog();
    changeState(STATUS_RESPONSE);
    LogUtil.i("response=", arg0);
    //		Bugtags.setUserData("response",arg0);
    // Jession失效,重新登陆
    if (arg0 != null && arg0.contains("http://www.w3.org/1999/xhtml")) {
      reLogin();

      return;
    }
    // json解析异常,提示服务器返回数据异常.
    try {

      onVolleyResponse(arg0);
    } catch (JSONException e) {
      LogUtil.e("Jsonerror=", e);
      ToastUtil.show(R.string.wrong_data);
    } catch (Exception e) {
      LogUtil.e("error=", e);
      //			ToastUtil.show(R.string.failure_operation);

    }
  }

  /**
   * 重新登陆
   */
  private void reLogin() {
    new AlertDialog.Builder(mContext).setMessage(R.string.loginLoseEficacy)
        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            AppManager.getAppManager().finishAllActivity();
            mContext.startActivity(new Intent(mContext, SplashActivity.class));
          }
        })
        .setCancelable(false)
        .show();
  }

  public abstract void onVolleyResponse(String json) throws JSONException;

  public int getState() {
    return state;
  }
}